import {
  HttpInterceptor,
  HttpRequest,
  HttpResponse,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse, HttpHeaders
} from '@angular/common/http';
import {Injectable} from "@angular/core";

import { Observable, throwError, from } from 'rxjs';
import { map, catchError, switchMap } from 'rxjs/operators';
import {Router} from "@angular/router";

import {AuthService} from "./auth.service";
import {StorageService} from './storage.service';


@Injectable()
export class MyHttpInterceptor implements HttpInterceptor{
  //统一配置网关地址，设置Http请求头，处理Http请求返回数据，统一错误处理等都是常见的需求。
  constructor(private storageService: StorageService
    ,private router:Router
    ,private authservice:AuthService
    ){

  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


    // const token = this.authenticationService.getToke()

    return from(this.storageService.get("TOKEN"))
      .pipe(
        switchMap(token => {
          if (token) {

            if(request.url.indexOf("/member/")!=-1||request.url.indexOf("/auth/")!=-1||request.url.indexOf("/employee/")!=-1){
              console.log('触犯读取TOken');
              request = request.clone({ headers: request.headers.set('Passport',  token) });
            }

          }
          else{
            //this.router.navigate(['/p401'])
            console.log('没有token');
            //this.eventbus.publish('LOGOUT');


          }


          // if (!request.headers.has('Content-Type')) {
          //   request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
          // }



          return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
              if (event instanceof HttpResponse) {
                // do nothing for now
                //  console.log(event.status);

                if(request.url.indexOf("/member/")!=-1||request.url.indexOf("/employee/")!=-1){


                  this.authservice.refreshToken();



                }




              }
              return event;
            }),
            catchError((error: HttpErrorResponse) => {
              const status =  error.status;
              //const reason = error && error.error.reason ? error.error.reason : '';

              //this.presentAlert(status, reason);
              //console.dir(error);
              if(error.status==401){
                // this.storage.remove("TOKEN")
                //   .then(()=>{
                //     this.router.navigate(['/p401']);
                //   })
                this.router.navigate(['/p401']);
              }


              if(error.status==403){
                //   this.storage.remove("TOKEN")
                //     .then(()=>{
                //       this.router.navigate(['/p403']);
                //     })
                //
                this.router.navigate(['/login']);
              }






              return throwError(error);
            })
          );
        })
      );
  }


  // intercept(req: HttpRequest<any>, next: HttpHandler) {
  //   // convert promise to observable using 'from' operator
  //   return from(this.handle(req, next))
  // }
  //
  //
  // async handle(request: HttpRequest<any>, next: HttpHandler) {
  //   // if your getAuthToken() function declared as "async getAuthToken() {}"
  //   //await this.auth.getAuthToken()
  //
  //   if(request.url.indexOf("/member/")!=-1||request.url.indexOf("/auth/")!=-1||request.url.indexOf("/employee/")!=-1){
  //     let token= await this.authservice.getTOken();
  //
  //     // if your getAuthToken() function declared to return an observable then you can use
  //     // await this.auth.getAuthToken().toPromise()
  //
  //     const authReq = request.clone({
  //       setHeaders: {
  //         "Passport": token
  //       }
  //     })
  //
  //     // Important: Note the .toPromise()
  //     return next.handle(authReq).toPromise()
  //   }
  //   else {
  //     return next.handle(request).toPromise()
  //   }
  //
  //
  //
  //
  // }


}
